﻿using System;
using System.Collections.Generic;
using System.Web;
using OctoOS;
using System.Web.Caching;

/// <summary>
/// Summary description for AppUtil
/// </summary>
public static class AppUtil
{
	private static LockPool<long> _lockPool = new LockPool<long>();
	private static Dictionary<long, ResourceInfo> _resourcesInfo = new Dictionary<long, ResourceInfo>();

	private const string _catPrefix = "rss";
	private static int _rssCatCnt = 30;
	private static int _rssMainCnt = 50;
	public static int maxFeaturedCnt = 4;
	private const int _autoPublishMinutes = 5;


	public static ResourceInfo GetResourceInfo(OOSRequest request)
	{
		ResourceInfo resourceInfo;

		lock(_lockPool.Get(request.ResourceID))
		{
			if(!_resourcesInfo.TryGetValue(request.ResourceID, out resourceInfo))
			{
				//инициализация ресурса
				ApiService.InitResource(request);

				var settings = ApiService.GetSettings(request);
				var categories = ApiService.GetCategories(request);

				resourceInfo = new ResourceInfo(settings, categories,
					DateTime.UtcNow.AddMinutes(_autoPublishMinutes));

				_resourcesInfo[request.ResourceID] = resourceInfo;
			}
		}

		return resourceInfo;
	}

	public static Settings GetSettings(OOSRequest request)
	{
		var resourceInfo = GetResourceInfo(request);
		return resourceInfo.Settings;
	}

	public static Category[] GetCategories(OOSRequest request)
	{
		var resourceInfo = GetResourceInfo(request);
		return resourceInfo.Categories;
	}

	public static Category GetCategory(OOSRequest request, long categoryID)
	{
		var categories = GetCategories(request);

		foreach(var category in categories)
		{
            if(category.IsCategory(categoryID))
                return category;
		}

		return null;
	}

	public static Category GetCategory(Category[] categories, long categoryID)
	{
		foreach(var category in categories)
		{
			if(category.IsCategory(categoryID))
				return category;
		}

		return null;
	}

	public static void RegularProcess(OOSRequest request)
	{
		//ApiService.DeleteAll(OOSRequest.Current);

		var resourceInfo = GetResourceInfo(request);
		if(DateTime.UtcNow > resourceInfo.AutoCloseCheckTime)
		{
			ApiService.AutoPublishArticles(request, DateTime.UtcNow);
			resourceInfo.AutoCloseCheckTime = DateTime.UtcNow.AddMinutes(_autoPublishMinutes);
		}
	}

	public static void UpdateCategoriesList(OOSRequest request)
	{
		lock(_lockPool.Get(request.ResourceID))
		{
			ResourceInfo resourceInfo;
			_resourcesInfo.TryGetValue(request.ResourceID, out resourceInfo);
			resourceInfo.Categories = ApiService.GetCategories(request);
		}	
	}

	public static void UpdateSettings(OOSRequest request)
	{
		lock(_lockPool.Get(request.ResourceID))
		{
			ResourceInfo resourceInfo;
			_resourcesInfo.TryGetValue(request.ResourceID, out resourceInfo);
			resourceInfo.Settings = ApiService.GetSettings(request);
		}
	}

	//не удалять
	//public static Article GetCachedArticle(OOSRequest request, long articleID)
	//{
	//    var article = HttpContext.Current.Cache[request.ResourceID +
	//        "article" + articleID] as Article;
	//    if(article != null)
	//        return article;

	//    article = HttpContext.Current.Cache[request.ResourceID +
	//        "article" + articleID] as Article;
	//    if(article != null)
	//        return article;

	//    article = ApiService.GetArticle(request, articleID);
	//    HttpContext.Current.Cache.Add(request.ResourceID + "article" + articleID,
	//        article, null, DateTime.UtcNow.AddMinutes(5),
	//        Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

	//    return article;
	//}

	public static MainPageArticlePreview[] GetMainRss(OOSRequest request)
	{
		//проверяем в кэше
		var articles = HttpContext.Current.Cache[request.ResourceID + _catPrefix] as MainPageArticlePreview[];
		if(articles != null)
			return articles;

		lock(_lockPool.Get(request.ResourceID))
		{
			articles = HttpContext.Current.Cache[request.ResourceID + _catPrefix] as MainPageArticlePreview[];
			if(articles != null)
				return articles;

			int totalCount;
			articles = ApiService.GetMainPreviews(request, 0, _rssMainCnt, out totalCount);

			HttpContext.Current.Cache.Add(
				request.ResourceID + _catPrefix,
				articles,
				null,
				DateTime.UtcNow.AddHours(2),
				Cache.NoSlidingExpiration,
				CacheItemPriority.Normal,
				null);
		}
		return articles;
	}

	public static CategoryArticlePreview[] GetCategoryRss(OOSRequest request, long categoryID)
	{
		//проверяем в кэше
		var articles = HttpContext.Current.Cache[request.ResourceID +
			_catPrefix + categoryID] as CategoryArticlePreview[];
		if(articles != null)
			return articles;

		lock(_lockPool.Get(request.ResourceID))
		{
			articles = HttpContext.Current.Cache[request.ResourceID +
			_catPrefix + categoryID] as CategoryArticlePreview[];
			if(articles != null)
				return articles;

			//считываем из бд, сохраняем в кэш на 2 часа и возвращаем
			//int totalCount;

			articles = ApiService.GetRSSCategoryArticles(request, categoryID,
				0, _rssCatCnt);//, out totalCount);

			HttpContext.Current.Cache.Add(
				request.ResourceID + _catPrefix + categoryID,
				articles,
				null,
				DateTime.UtcNow.AddHours(2),
				Cache.NoSlidingExpiration,
				CacheItemPriority.Normal,
				null);
		}

		return articles;
	}

	public static string GetEncodedTitle(string title)
	{
		return HtmlUtility.UrlPathLevelEncode(title, 100, true);
	}
}


public enum CommentsEnabled
{
	Disabled = 1,
	Registered,
	Anonymous
}

public enum CommentsModeration
{
	Always = 1,
	Anonymous,
	Never
}

public enum FeedMode
{
	None = 1,
	Short,
	Full
}

public enum CompleteStatus
{
	PrivateDraft = 0,
	PublicDraft,
	Completed
}
